package com.bey.bow.service.tutorial;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.DateProvider;

import com.bey.bow.entity.Tutorial;
import com.bey.bow.repository.TutorialDao;

@Component
@Transactional(readOnly = true)
public class TutorialService {

	private TutorialDao tutorialDao;

	private DateProvider dateProvider = DateProvider.DEFAULT;

	@Transactional(readOnly = false)
	public void saveTutorial(Tutorial entity) {
		entity.setTutorialDate(dateProvider.getDate());
		tutorialDao.save(entity);
	}

	public Tutorial getTutorial(Long id) {
		return tutorialDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void deleteTutorial(Long id) {
		tutorialDao.delete(id);
	}

	public Page<Tutorial> getTutorials(int pageNumber, int pageSize, String sortType) {

		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize,
				sortType);
		return tutorialDao.findAll(pageRequest);

	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,
			String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("date".equals(sortType)) {
			sort = new Sort(Direction.DESC, "tutorialDate");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	@Autowired
	public void setTutorialDao(TutorialDao tutorialDao) {
		this.tutorialDao = tutorialDao;
	}

}
